'''
 Copyright (c) 2012, Peter Angyal <angyalp@gmail.com>
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
     * Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
     * Neither the name of the <organization> nor the
       names of its contributors may be used to endorse or promote products
       derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''

import xml.etree.ElementTree as ET

class TrackPath(object):
    
    def __init__(self):
        self._sections = []


    def _loadPathDataFromSVGFile(self, svgFileName, pathID):
        try:
            xmlTree = ET.parse(svgFileName)
        except ET.ParseError as e:
            row, column = e.position
            print "Track file error: ", row, ",", column, ": ", e
            return None
        except IOError as e:
            print "I/O error: ", e
            return None
    
        rootElem = xmlTree.getroot()

        svgURI = "{http://www.w3.org/2000/svg}"
        searchStr = ".//" + svgURI + "path[@id='" + pathID + "']"

        pathElem = rootElem.find(searchStr)
        if pathElem is None:
            return None

        pathData = pathElem.attrib['d']
        return pathData
    
    
    
    
    def _interpolatePath(self, pathCommands):
        '''
        Path object is an interpolation of the path by line sections.
        The path is always closed: The end-point of the last section is the start-point of the first section.
        The path is never empty.
        '''
        pass
        

    def _parsePoint(self, strPoint):
        return map(float, strPoint.split(","))

    def _parsePathData(self, pathData):
        '''
        Returns the path commands from an SVG path data.
        The returned commands are simplified:
        - The commands are not compressed, i.e. one command contains parameters for only one command.
        The path is never empty: A valid path must contain at least one command beside M and Z.
        Valid path data is only a subset of the valid SVG path data format:
        - There must be a separator between the command and its parameters.
        - There must be a separator between a command and the parameters of the previous command.
        - Only M, Z, C, L, H and V commands (and their relative versions) are allowed. 
        '''
        
        if pathData[0].upper() != "M":
            # Moveto is not the first command.
            return None
        
        dataWords = pathData.split()
        prevCommand = ""
        commandList = []
        
        while len(dataWords) != 0:
            # Continuation of previous command
            if not dataWords[0].isalpha():
                dataWords.insert(0, prevCommand)
                continue
            
            # Command starts with command character
            command = dataWords.pop(0)
            
            # Read parameters    
            params = []
            if command.upper() == "M":
                params.append(self._parsePoint(dataWords.pop(0)))
            elif command.upper() == "C":
                for i in range(3):
                    params.append(self._parsePoint(dataWords.pop(0)))
            elif command.upper() == "Z":
                if len(dataWords) != 0:
                    # Closepath is not the last command.
                    return None
            else:
                # Invalid command
                return None
            
            # Store command and parameters
            commandList.append([command, params])
            
            # Storing actual command in case of additional parameters for the actual command.
            # Additional parameters of m/M should be treated as parameters of l/L command.
            if command == "m":
                prevCommand = "l"
            elif command == "M":
                prevCommand = "L"
            else:
                prevCommand = command
        
        print pathData
        print commandList
        
        return commandList
    

    def getSections(self):
        return self._sections
    
    
    def parseFromSVGFile(svgFileName, pathElemID):
        trackPath = TrackPath()
        
        pathData = trackPath._loadPathDataFromSVGFile(svgFileName, pathElemID)
        if pathData is None:
            return None
        
        pathCommands = trackPath._parsePathData(pathData)
        if pathCommands is None:
            return None
        
        trackPath._interpolatePath(pathCommands)
        
        return trackPath
    
    parseFromSVGFile = staticmethod(parseFromSVGFile)
